package com.xiyuan.smartutils.xml.parser;

import com.xiyuan.smartutils.Ints;
import com.xiyuan.smartutils.Longs;
import com.xiyuan.smartutils.StrUtils;
import com.xiyuan.smartutils.constants.XmlConstants;
import com.xiyuan.smartutils.xml.Xml;
import com.xiyuan.smartutils.xml.XmlParser;
import com.xiyuan.smartutils.xml.Xmls;
import org.w3c.dom.Node;

/**
 * 基本类型适配器，格式如下：
 * <ID>19202129384</ID>
 *
 * @version v1.1.2 @author lgz 2017-8-21 新建与整理
 */
public class BaseParser implements XmlParser, XmlConstants
{
    @Override
    public XmlParser set(Xml xmlMain)
    {
        return this;
    }
    
    @Override
    public String toStringInner(Object obj, String tagName, int tagLevel)
    {
        StringBuilder strb = new StringBuilder();
        StrUtils.addNewLine(strb);
        StrUtils.addTwoSpace(strb, tagLevel);
        
        Xmls.addTagBegin(strb, tagName);
        if (obj instanceof String && ((String)obj).contains("<"))
            strb.append(_CDATA).append(obj).append(CDATA_);
        else
            strb.append(obj);
        Xmls.addTagEnd(strb, tagName);
        return strb.toString();
    }
    
    @Override
    public Object toObjectInner(Node node, Class<?> clazz, Class<?> generics)
    {
        if (node == null)
        {//没有节点返回null
            return null;
        }
        
        String xml = node.getTextContent();
        if (clazz == boolean.class || clazz == Boolean.class)
            return Boolean.parseBoolean(xml);
        else if (clazz == byte.class || clazz == Byte.class)
            return Byte.parseByte(xml);
        else if (clazz == char.class || clazz == Character.class)
            return xml.charAt(0);
        else if (clazz == short.class || clazz == Short.class)
            return Short.parseShort(xml);
        else if (clazz == int.class || clazz == Integer.class)
            return Ints.toInt(xml);
        else if (clazz == long.class || clazz == Long.class)
            return Longs.toLong(xml);
        else if (clazz == float.class|| clazz == Float.class)
            return Float.parseFloat(xml);
        else if (clazz == double.class || clazz == Double.class)
            return Double.parseDouble(xml);
        else if (clazz == String.class)
            return xml;
        else
            return null;
    }
}
